﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Text.RegularExpressions;
using System.Threading;

namespace JustPlus
{
    /// <summary>
    /// OperationPanel.xaml 的交互逻辑
    /// </summary>
    public partial class OperationPanel : UserControl
    {
        //public static string logoutUrl="";
        private float sopacity = 0.6f;
        private Image[] ImageCell;
        private string[] stringCell;
        public OperationPanel()
        {
            InitializeComponent();
            ImageCell = new Image[8] { image1, image2, image3, image4, image5, image6, image7, image8 };
            stringCell = new string[8] { "频道选择", "搜索音乐", "音乐基因", "登录", "设置", "帮助", "更新", "关于" };
            SetOpacity(0.0f);
        }

        public void SetOpacity(float opacity)
        {
            foreach (Image image in ImageCell)
                image.Opacity = opacity;
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < 8; i++)
            {
                ImageCell[i].MouseEnter += new MouseEventHandler(Elem_MouseEnter);
                ImageCell[i].MouseLeave += new MouseEventHandler(Elem_MouseLeave);
                ImageCell[i].Tag = stringCell[i];
            }
        }

        private void Elem_MouseEnter(object sender, MouseEventArgs e)
        {
            Point pt = e.GetPosition(this);
            //System.Diagnostics.Debug.WriteLine(pt.X.ToString() + " " + pt.Y.ToString());
            if (pt.X + pt.Y <= 1)
                return;
            Image image = sender as Image;
            image.Opacity = 1.0;
            label1.Content = image.Tag.ToString();
        }

        private void Elem_MouseLeave(object sender, MouseEventArgs e)
        {
            Point pt = e.GetPosition(this);
            if (pt.X >= 256)
                return;
            Image image = sender as Image;
            image.Opacity = sopacity;
            label1.Content = "";
        }

        private void Grid_MouseEnter(object sender, MouseEventArgs e)
        {
            //考虑：鼠标移入时，专辑封面半透明，以使菜单项更清晰
            Point pt = e.GetPosition(this);
            //System.Diagnostics.Debug.WriteLine(pt.X.ToString() + " " + pt.Y.ToString());
            if (pt.X + pt.Y <= 1)
                return;
            //System.Diagnostics.Debug.WriteLine(pt.X.ToString() + " " + pt.Y.ToString());
            MainWindow mwnd = (MainWindow)Application.Current.MainWindow;
            mwnd.stackPanel2.Background = new SolidColorBrush(Colors.Transparent);

            SetOpacity(sopacity);
            Grid grid = sender as Grid;
            grid.ShowGridLines = true;
        }

        private void Grid_MouseLeave(object sender, MouseEventArgs e)
        {
            Point pt = e.GetPosition(this);
            //System.Diagnostics.Debug.WriteLine(pt.X.ToString() + " " + pt.Y.ToString());
            if (pt.X >= 256)
                return;
            MainWindow mwnd = (MainWindow)Application.Current.MainWindow;
            //修订：窗口退出时，触发leave事件，但是mwnd=null
            if (mwnd == null )
                return;
            mwnd.stackPanel2.Background = PlayerPanel.bkbrush;

            SetOpacity(0.0f);
            Grid grid = sender as Grid;
            grid.ShowGridLines = false;
        }

        //判断服务器端是否已登录
        private void HasLogined()
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback((state) =>
                {
                    string loginresult = new ConnectionBase().Get(@"http://douban.fm/");
                    if (string.IsNullOrEmpty(loginresult))
                    {
                        //label7.Content = "搜索失败，请检查网络或者尝试重新搜索！";
                        LoginPanel.HasLoginOn = false;
                        Dispatcher.Invoke(new Action(() =>
                            {
                                MainWindow mwnd = (MainWindow)Application.Current.MainWindow;
                                mwnd.stackPanel1.Children.Clear();
                                //ConnectionBase.cc = ConnectionBase.DefaultCookie;
                                LoginPanel loginpanel = new LoginPanel();
                                mwnd.stackPanel1.Children.Add(loginpanel);
                            }));
                        return;
                    }
                    else
                    {
                        /*MatchCollection mc = Regex.Matches(loginresult, @"<div class=""login"">(\s.*?)*</ul>", RegexOptions.IgnoreCase);
                        if (mc.Count == 0)
                        {
                            LoginPanel.HasLoginOn = false;
                        }
                        else
                        {
                            string temp = mc[0].Groups[0].Value;
                            string userurl = Regex.Match(temp, @"<a href=\""([^\""]+)\"" id=\""fm-user\"">", RegexOptions.IgnoreCase).Groups[1].Value;
                            string username = Regex.Match(temp, @"id=\""fm-user\"">([^\""]+)<i></i></a>", RegexOptions.IgnoreCase).Groups[1].Value;
                            if (userurl == @"{{= user.url }}" || username == @"{{= user.name }}")
                            {
                                LoginPanel.HasLoginOn = false;
                            }
                            else
                            {
                                LoginPanel.HasLoginOn = true;
                                string played = Regex.Match(temp, @"<a href=""/mine\?type=played"" target=""_blank"">累积收听<i>(\d+)</i>首</a>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                                string liked = Regex.Match(temp, @"<a href=""/mine\?type=liked"" target=""_blank"">加红心<i>(\d+)</i>首</a>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                                string banned = Regex.Match(temp, @"<a href=""/mine\?type=banned"" target=""_blank""><i>(\d+)</i>首不再播放</a>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                                LoginPanel.LoginName = username;
                                LoginPanel.LoginPlayed = Int32.Parse(played);
                                LoginPanel.LoginLiked = Int32.Parse(liked);
                                LoginPanel.LoginBanned = Int32.Parse(banned);
                            }
                        }*/
                        Match match = Regex.Match(loginresult, @"var\s*globalConfig\s*=\s*{\s*uid\s*:\s*'(\d*)'", RegexOptions.IgnoreCase);
                        string s = match.Groups[1].Value;
                        Match match2 = Regex.Match(loginresult, @"id=""fm-user"">(?!{{)(.*)<i></i></a>", RegexOptions.None);
                        string nickname = match2.Groups[1].Value;
                        Match match3 = Regex.Match(loginresult, @"累积收听.*?(\d+).*?首");
                        int played = 0;
                        int.TryParse(match3.Groups[1].Value, out played);
                        Match match4 = Regex.Match(loginresult, @"加红心.*?(\d+).*?首");
                        int liked = 0;
                        int.TryParse(match4.Groups[1].Value, out liked);
                        Match match5 = Regex.Match(loginresult, @"(\d+).*?首不再播放");
                        int banned = 0;
                        int.TryParse(match5.Groups[1].Value, out banned);
                        //Match match6 = Regex.Match(loginresult, @"<a href=\""([^\""\{]*?)\"">退出</a>");
                        //logoutUrl = match6.Groups[1].Value;
                        if (!string.IsNullOrEmpty(s))
                        {
                            LoginPanel.LoginPlayed = played;
                            LoginPanel.LoginLiked = liked;
                            LoginPanel.LoginBanned = banned;
                            LoginPanel.HasLoginOn = true;
                            Dispatcher.Invoke(new Action(() =>
                            {
                                MainWindow mwnd = (MainWindow)Application.Current.MainWindow;
                                mwnd.stackPanel1.Children.Clear();
                                LogoutPanel logoutpanel = new LogoutPanel();
                                mwnd.stackPanel1.Children.Add(logoutpanel);
                                logoutpanel.label1.Content = LoginPanel.LoginName;
                                logoutpanel.label2.Content = "累计收听" + LoginPanel.LoginPlayed.ToString() + "首";
                                logoutpanel.label3.Content = "加红心" + LoginPanel.LoginLiked.ToString() + "首";
                                logoutpanel.label4.Content = "不再收听" + LoginPanel.LoginBanned.ToString() + "首";
                            }));
                        }
                        else
                        {
                            LoginPanel.HasLoginOn = false;
                            Dispatcher.Invoke(new Action(() =>
                            {
                                MainWindow mwnd = (MainWindow)Application.Current.MainWindow;
                                mwnd.stackPanel1.Children.Clear();
                                //ConnectionBase.cc = ConnectionBase.DefaultCookie;
                                LoginPanel loginpanel = new LoginPanel();
                                mwnd.stackPanel1.Children.Add(loginpanel);
                            }));
                        }
                    }
                }));
        }

        //==>登录豆瓣账户
        private void image4_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
 /*           MainWindow mwnd = (MainWindow)Application.Current.MainWindow;
            mwnd.stackPanel1.Children.Clear();
            if (LoginPanel.HasLoginOn == false)
            {
                ConnectionBase.cc = ConnectionBase.DefaultCookie;
                LoginPanel loginpanel = new LoginPanel();
                mwnd.stackPanel1.Children.Add(loginpanel);
            }
            else
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback((state) =>
                {
                    string loginresult = new ConnectionBase().Get(@"http://douban.fm/");
                    if (string.IsNullOrEmpty(loginresult))
                    {
                        Dispatcher.Invoke(new Action(() =>
                        {
                            LogoutPanel logoutpanel = new LogoutPanel();
                            mwnd.stackPanel1.Children.Add(logoutpanel);
                            logoutpanel.label6.Content = @"加载失败，请检查网络或者尝试重新登录！";
                            logoutpanel.label6.Opacity = 1;
                        }));
                        LoginPanel.HasLoginOn = false;
                    }
                    else
                    {
                        Match match = Regex.Match(loginresult, @"var\s*globalConfig\s*=\s*{\s*uid\s*:\s*'(\d*)'", RegexOptions.IgnoreCase);
                        string s = match.Groups[1].Value;
                        //Match match6 = Regex.Match(loginresult, @"<a href=\""([^\""\{]*?)\"">退出</a>");
                        //logoutUrl = match6.Groups[1].Value;
                        if (!string.IsNullOrEmpty(s))
                        {
                            Match match2 = Regex.Match(loginresult, @"id=""fm-user"">(?!{{)(.*)<i></i></a>", RegexOptions.None);
                            string nickname = match2.Groups[1].Value;
                            Match match3 = Regex.Match(loginresult, @"累积收听.*?(\d+).*?首");
                            int played = 0;
                            int.TryParse(match3.Groups[1].Value, out played);
                            Match match4 = Regex.Match(loginresult, @"加红心.*?(\d+).*?首");
                            int liked = 0;
                            int.TryParse(match4.Groups[1].Value, out liked);
                            Match match5 = Regex.Match(loginresult, @"(\d+).*?首不再播放");
                            int banned = 0;
                            int.TryParse(match5.Groups[1].Value, out banned);
                            Dispatcher.Invoke(new Action(() =>
                            {
                                LogoutPanel logoutpanel = new LogoutPanel();
                                mwnd.stackPanel1.Children.Add(logoutpanel);
                                logoutpanel.label6.Opacity = 0;
                                logoutpanel.label1.Content = nickname;
                                logoutpanel.label2.Content = "累计收听" + played.ToString() + "首";
                                logoutpanel.label3.Content = "加红心" + liked.ToString() + "首";
                                logoutpanel.label4.Content = "不再收听" + banned.ToString() + "首";
                            }));
                        }
                        else
                        {
                            LoginPanel.HasLoginOn = false;
                            Dispatcher.Invoke(new Action(() =>
                            {
                                LoginPanel loginpanel = new LoginPanel();
                                mwnd.stackPanel1.Children.Add(loginpanel);
                            }));
                        }
                    }
                }));
            }*/
            HasLogined();
        }

        //==>关于软件
        public void image8_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MainWindow mwnd = (MainWindow)Application.Current.MainWindow;
            AboutPanel aboutpanel = new AboutPanel();
            mwnd.stackPanel1.Children.Clear();
            mwnd.stackPanel1.Children.Add(aboutpanel);
        }

        //==>软件设置
        public void image5_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MainWindow mwnd = (MainWindow)Application.Current.MainWindow;
            SettingPanel settingpanel = new SettingPanel();
            mwnd.stackPanel1.Children.Clear();
            mwnd.stackPanel1.Children.Add(settingpanel);
        }

        //==>频道选择
        private void image1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MainWindow mwnd = (MainWindow)Application.Current.MainWindow;
            ChannelPanel channelpanel = new ChannelPanel();
            mwnd.stackPanel1.Children.Clear();
            mwnd.stackPanel1.Children.Add(channelpanel);
        }

        //==>帮助信息
        private void image6_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MainWindow mwnd = (MainWindow)Application.Current.MainWindow;
            HelpPanel helppanel = new HelpPanel();
            mwnd.stackPanel1.Children.Clear();
            mwnd.stackPanel1.Children.Add(helppanel);
        }

        //==>音乐基因
        private void image3_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MainWindow mwnd = (MainWindow)Application.Current.MainWindow;
            GenePanel genepanel = new GenePanel();
            mwnd.stackPanel1.Children.Clear();
            mwnd.stackPanel1.Children.Add(genepanel);
        }

        //==>搜索音乐
        private void image2_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MainWindow mwnd = (MainWindow)Application.Current.MainWindow;
            SearchPanel searchpanel = new SearchPanel();
            mwnd.stackPanel1.Children.Clear();
            mwnd.stackPanel1.Children.Add(searchpanel);
        }
    }
}
